package com.taotao.netty.socket.multiclient.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Description: 服务器端处理器
 * @Author: TaoJF
 * @Date: Created in 2018/6/28 下午9:31
 */
public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {

    //保存所有的连上的channel
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.forEach(ch -> {
            if (channel != ch) {
                ch.writeAndFlush(channel.remoteAddress() + "发送的消息：" + msg + "\n");
            } else {
                ch.writeAndFlush("[自己]： " + msg + "\n");
            }
        });


    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + " 上线！");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + " 下线！");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " 加入！");
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[服务器] - " + channel.remoteAddress() + "加入\n");
        channelGroup.add(channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " 离开！");
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[服务器] - " + channel.remoteAddress() + " 离开\n");
        System.out.println("当前剩余的客户端个数：" + channelGroup.size());
    }

    public static void reportAllClientChannelGroup() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Thread thread = new Thread(() -> {
            for (; ; ) {
                channelGroup.forEach(channel1 -> {
                    try {
                        channel1.writeAndFlush(String.format("服务器通知：%s\r\n", br.readLine()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        });
        thread.start();
    }



}
